package com.example.simplesvc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.concurrent.ExecutorService;

@RestController
public class SimpleController {


    private static Logger logger = LoggerFactory.getLogger(SimpleController.class);




    @Autowired
    ExamplePromleService examplePromleService;

    @Autowired
    MySpringServiceWithExecutor msswe;

    @Autowired
    MySpringServiceWithTimer msswt;

    @Autowired
    MySpringServiceWithThread msswtr;

    public SimpleController() {

        logger.info("------------------inited");
    }

    @GetMapping("/hi/{t}")
    public ResponseEntity hi(@PathVariable("t") String t) {

        examplePromleService.startAUnstopThread();
        return ResponseEntity.ok("hi"+System.currentTimeMillis());

    }

    @GetMapping("/hello")
    public ResponseEntity hello() {

        examplePromleService.createInstanceOutOfSpringContext();
        return ResponseEntity.ok("hello"+System.currentTimeMillis());

    }



    @Qualifier("coreExecutor")
    @Autowired
    ExecutorService es;
    @GetMapping("/core/hi")
    public ResponseEntity coreHi() {

        es.submit(new Runnable() {
            @Override
            public void run() {
                for(;;) {
                    logger.info("core hi running -----");

                    try {
                        Thread.sleep(5000);
                    }catch (InterruptedException e) {
                        logger.info("thread interrupted ,return ");
                        return;
                    }
                }
            }
        });

        return ResponseEntity.ok("core-hi-success");
    }




    @GetMapping("/spring/{t}")
    public ResponseEntity helloSpring(@PathVariable("t") String t) {

        if(Objects.equals(t,"1")) {
            msswe.runTask();
        } else if(Objects.equals(t,"2")){
            msswt.runTask();
        }

        return ResponseEntity.ok("springPoolTaskExecutor"+System.currentTimeMillis());
    }

    @GetMapping("/message/{msg}")
    public ResponseEntity message(@PathVariable("msg") String msg) {

        logger.info("received {}", msg);

        return ResponseEntity.ok(msg);

    }



}
